package com.project_doctor.handler.dropped;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.fastjson2.JSONArray;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class IntegerListConverter implements Converter<List<Integer>> {

    @Override
    public Class<List<Integer>> supportJavaTypeKey() {
        return (Class<List<Integer>>) (Class<?>) List.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 导出时：将List<Integer>转换为Excel单元格数据（字符串）
     */
    @Override
    public WriteCellData<?> convertToExcelData(List<Integer> value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        if (value == null || value.isEmpty()) {
            return new WriteCellData<>("");
        }
        // 转换为逗号分隔的字符串
        return new WriteCellData<>(value.stream()
                .map(String::valueOf)
                .collect(Collectors.joining(",")));
    }

    /**
     * 导入时：将Excel单元格数据转换为List<Integer>
     * 支持多种格式：
     * 1. 逗号分隔的数字："113,114"
     * 2. JSON数组格式："[113,114]"
     */
    @Override
    public List<Integer> convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                           GlobalConfiguration globalConfiguration) {
        if (cellData == null || cellData.getStringValue() == null) {
            return new ArrayList<>();
        }

        String cellValue = cellData.getStringValue().trim();
        List<Integer> result = new ArrayList<>();

        // 处理JSON数组格式
        if (cellValue.startsWith("[") && cellValue.endsWith("]")) {
            try {
                JSONArray array = JSONArray.parseArray(cellValue);
                for (int i = 0; i < array.size(); i++) {
                    result.add(array.getInteger(i));
                }
                return result;
            } catch (Exception e) {
                // 解析失败时按普通字符串处理
            }
        }

        // 处理逗号分隔的字符串
        String[] parts = cellValue.split(",");
        for (String part : parts) {
            try {
                result.add(Integer.parseInt(part.trim()));
            } catch (NumberFormatException e) {
                // 跳过无法转换的元素
            }
        }

        return result;
    }
}